var React = require('react');
var Checkbox = require('../Checkbox');
var Input = require('../Input');
var Icon = require('../Icon');

module.exports = React.createClass({
	displayName:'TableRow',
	getInitialState:function(){
		return {
			selected: this.props.selected,
			editable: this.props.editable
		}
	},
	componentDidMount:function(){
		this.props.onDidMount && this.props.onDidMount(this);
	},
	checked: function (value){
		this.refs.checkbox && this.refs.checkbox.checked(value);
	},
	selected: function (selected) {
		this.setState({
			selected: selected
		});
	},
	editable: function (editable) {
		this.setState({
			editable: editable
		});
	},
	__onCheckBoxChange: function (event, value, cb){
		this._checked = value;
		this.props.onCheckBoxChange && this.props.onCheckBoxChange(value, this, cb);
	},
	__onRowClick: function (event){
		var _td = this.__getTargetTD(event.target),
			_tr = this.getDOMNode();
		this.props.onRowClick && this.props.onRowClick(event, {
			tr: _tr,
			td: _td,
			data: this.props.data,
			items: this.props.items
		}, this);
	},
	__getTargetTD: function (target) {
		if(target.tagName!=='TD'){
			return this.__getTargetTD(target.parentNode);
		} else {
			return target;
		}
	},
	__columnRender: function (item, index){
		var _value = this.props.data,
			_content = null;

		if(Object.prototype.toString.call(_value) === '[object Array]'){
			if(this.props.checkbox){
				_value = _value[index-1]
			}else {
				_value = _value[index]
			}
		} else {
			_value = _value[item.name];
		}

		if(this.props.columnRender){
			_content = this.props.columnRender(index, this.props.data, item, _value);
		}

		if(_content == null){
			switch (item.type) {
				case 'checkbox':
					_content = this.state.editable?<Icon icon="fa-edit" />:<Checkbox onChange={this.__onCheckBoxChange} ref="checkbox" checked={_value} />;
					break;
				default:
					_content = this.state.editable?<Input {...item} />:<span>{_value}</span>;
					break;
			}
		}

		return <td key={index} className={'text-align-'+(item.textAlign||'left')}>{_content}</td>;
	},
	render:function(){
		return (
			<tr className={"row " + (this.state.editable?'editable':'') + " " + (this.state.selected?'selected':'')} onClick={this.__onRowClick}>
				{
					(this.props.items||[]).map(this.__columnRender)
				}
			</tr>
		);
	}
});
